package jmu.controller;

import jakarta.servlet.http.HttpSession;
import jmu.service.MessageService;
import jmu.service.RevertService;
import jmu.vo.Message;
import jmu.vo.Revert;
import jmu.vo.Students;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/messages")
public class MessageController {
    @Autowired
    private MessageService messageService;

    @Autowired
    private RevertService revertService;

    @GetMapping("/list")
    public String list(Model model) {
        List<Message> messages = messageService.list();

        Map<Integer, List<Revert>> revertsMap = new HashMap<>();
        for (Message message : messages) {
            List<Revert> reverts = revertService.findRevert(message.getMessageID());
            revertsMap.put(message.getMessageID(), reverts);
        }

        model.addAttribute("messages", messages);
        model.addAttribute("revertsMap", revertsMap);
        return "message/list";
    }

    @GetMapping("/add")
    public String showAddForm() {
        return "message/add";
    }

    @PostMapping("/add")
    public String add(@ModelAttribute Message message) {
        messageService.add(message);
        return "redirect:/messages/list";
    }

    @GetMapping("/edit/{id}")
    public String showEditForm(@PathVariable int id, HttpSession session, Model model) {
        Students currentUser = (Students) session.getAttribute("currentUser");
        if (currentUser == null) {
            return "redirect:/students/login";
        }
        Message message = messageService.findMessageById(id);
        if (message == null) {
            return "redirect:/messages/list";
        }

        // 权限校验
        if (!message.getWriter().equals(currentUser.getStudentName())) {
            model.addAttribute("error", "无操作权限");
        }

        model.addAttribute("message", message);
        return "message/edit";
    }

    @PostMapping("/update")
    public String update(@ModelAttribute Message message, HttpSession session, Model model) {
        // 1. 校验登录状态
        Students currentUser = (Students) session.getAttribute("currentUser");
        if (currentUser == null) {
            return "redirect:/students/login";
        }

        // 2. 二次校验操作权限
        if (!message.getWriter().equals(currentUser.getStudentName())) {
            model.addAttribute("error", "非法操作：您无权修改此留言");
            return "message/edit"; // 返回编辑页显示错误
        }

        // 3. 执行更新并检查结果
        boolean updateResult = messageService.update(message);
        if (updateResult) {
            return "redirect:/messages/list"; // 成功重定向
        } else {
            model.addAttribute("error", "留言更新失败，请稍后重试");
            model.addAttribute("message", message); // 重新绑定数据
            return "message/edit"; // 返回编辑页显示错误
        }
    }

    @GetMapping("/delete/{id}")
    public String delete(@PathVariable int id,
                         HttpSession session,
                         RedirectAttributes redirectAttributes) {
        // 1. 检查登录状态
        Students currentUser = (Students) session.getAttribute("currentUser");
        if (currentUser == null) {
            redirectAttributes.addFlashAttribute("error", "请先登录");
            return "redirect:/students/login";
        }

        // 2. 获取留言信息
        Message message = messageService.findMessageById(id);
        if (message == null) {
            redirectAttributes.addFlashAttribute("error", "留言不存在");
            return "redirect:/messages/list";
        }

        // 3. 权限校验
        if (!message.getWriter().equals(currentUser.getStudentName())) {
            redirectAttributes.addFlashAttribute("error", "无权删除他人留言");
            return "redirect:/messages/list";
        }

        // 4. 执行删除
        if (messageService.delete(id)) {
            redirectAttributes.addFlashAttribute("deleteSuccess", true);
        } else {
            redirectAttributes.addFlashAttribute("error", "删除失败");
        }

        return "redirect:/messages/list";
    }

    @GetMapping("/search")
    public String search(@RequestParam String keyword, Model model) {
        List<Message> messages = messageService.search(keyword);

        Map<Integer, List<Revert>> revertsMap = new HashMap<>();
        for (Message message : messages) {
            List<Revert> reverts = revertService.findRevert(message.getMessageID());
            revertsMap.put(message.getMessageID(), reverts);
        }

        model.addAttribute("messages", messages);
        model.addAttribute("keyword", keyword);
        model.addAttribute("revertsMap", revertsMap); // 新增关键属性
        return "message/list";
    }
}